package com.hanhai.material.config.security;

import com.hanhai.material.common.constant.Constant;
import com.hanhai.material.utils.redis.RedisUtil;
import com.hanhai.material.wages.entity.SysUser;
import com.hanhai.material.wages.service.SysUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Log4j2
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    RedisUtil redisUtil;

    /*用户登录验证*/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        /*设置30分钟有效*/
//        this.redisUtil.hset(sysUser.getUsername(), Constant.USER_NAME, sysUser.getUsername(), 3 * 10 * 60);
        this.redisUtil.hset(sysUser.getUsername(), Constant.USER_NAME, sysUser.getUsername());

        return new UserDetail(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), sysUser.isEnabled(), getUserAuthority(sysUser.getId()));
    }

    /**
     * 获取用户权限信息
     *
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(String userId) {
        String authority = sysUserService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
